//
//  WelcomViewController.m
//  clublbiza
//
//  Created by WANG TOM on 7/16/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "WelcomViewController.h"
#import "clublbizaAppDelegate.h"
#import "MainViewController.h"
#import "SettingViewController.h"

@interface WelcomViewController ()

@end

@implementation WelcomViewController
@synthesize infoView;
@synthesize activityView;
@synthesize mainBackgroundImage;
@synthesize gotoSettingBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self refreshBackGrounImage];
    
}
- (void) refreshBackGrounImage
{
    NSString *defaultKeyName = APPLICATION_BACKGROUND_IMAGE_NAME_1;
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *isCustomize = [userDefaults stringForKey:defaultKeyName];
    if (isCustomize != nil){
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        
        NSString *bgImgPath = [documentsPath stringByAppendingFormat:@"/%@",defaultKeyName];
        UIImage *image = [UIImage imageWithContentsOfFile:bgImgPath];
        self.mainBackgroundImage.image = image;
    }else {
        UIImage *image = [UIImage imageNamed:@"bg1.jpg"];
        self.mainBackgroundImage.image = image;
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    settingdialogopend = NO;
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(refreshInfoView:)
                                                 name: @"BACKGROUND_SYNC_THREAD_STATUS"
                                               object: nil];

    //star background sync thred
    [self latterStartSyncBackgrounThread];
}

- (void) latterStartSyncBackgrounThread
{
    [NSTimer scheduledTimerWithTimeInterval: 3  
                                                  target: self  
                                                selector: @selector(latterStartSyncBackgrounThreadHandler)  
                                                userInfo: nil  
                                                 repeats: NO];
}
- (void) latterStartSyncBackgrounThreadHandler
{
    if ( settingdialogopend ) {
        return;
    }

    self.activityView.hidden = NO;
    self.gotoSettingBtn.hidden = YES;
    clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    [appDelegate startSyncBackgroundThread]; 
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.infoView = nil;
    self.activityView = nil;
    self.mainBackgroundImage = nil;
    self.gotoSettingBtn = nil;
  
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}
- (void) refreshInfoView:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
   NSString *msg = [info objectForKey:@"msg"];
   
    UIColor *color = [UIColor whiteColor];
    bool stopActivityView = FALSE;
    bool hasError = FALSE;
    if ([[info objectForKey:@"type"] isEqualToString:@"ERROR"]) {
        color = [UIColor redColor];
        stopActivityView = TRUE;
        hasError = TRUE;
    }
    bool isDone = FALSE;
    if ([[info objectForKey:@"type"] isEqualToString:@"DONE"]) {
        stopActivityView = TRUE;
        isDone = TRUE;
    }
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
    if ( color != nil ) {
     [self performSelectorOnMainThread:@selector(threadPerformSetMessageColor:) withObject:color waitUntilDone:YES];
    }
    [self performSelectorOnMainThread:@selector(threadPerformSetMessageContent:) withObject:msg waitUntilDone:YES];  
    if (stopActivityView) {

        
       [self performSelectorOnMainThread:@selector(threadPerformStopActivityView) withObject:nil waitUntilDone:YES]; 
    }
    
    if( isDone ) {
        [self performSelectorOnMainThread:@selector(jumpToUserMainView) withObject:nil waitUntilDone:YES]; 
      //  [self performSelectorOnMainThread:@selector(threadPerformConfirmDialog:) withObject:@"同步数据完成" waitUntilDone:YES]; 
     }
    if ( hasError ) {
        //[self performSelectorOnMainThread:@selector(threadPerformConfirmDialog:) withObject:@"同步数据错误" waitUntilDone:YES]; 
        
        [self performSelectorOnMainThread:@selector(latterGotoMainView) withObject:nil waitUntilDone:YES]; 
      
    }
    [pool release];  
}
- (void) latterGotoMainView
{
    self.gotoSettingBtn.hidden = NO;
    [NSTimer scheduledTimerWithTimeInterval: 5  
                                     target: self  
                                   selector: @selector(latterGotoMainViewCore)  
                                   userInfo: nil  
                                    repeats: NO];
}
- (void) latterGotoMainViewCore
{
    if ( settingdialogopend ) {
        return;
    }
    [self performSelectorOnMainThread:@selector(jumpToUserMainView) withObject:nil waitUntilDone:YES]; 
}
- (void) threadPerformSetMessageContent:(NSString*)msg
{
    
    self.infoView.text = msg;
}
- (void) threadPerformSetMessageColor:(UIColor*)color
{
    self.infoView.textColor = color;
   
}
- (void) threadPerformStopActivityView
{
    [self.activityView stopAnimating];
    self.activityView.hidden = TRUE;
}
- (void) threadPerformConfirmDialog:(NSString *)dialogTitle
{
    
    UIAlertView *alert = [[UIAlertView alloc] 
                          initWithTitle: NSLocalizedString(dialogTitle,nil)
                          message: [NSString stringWithFormat:@"%@，更高设置或者之间进入APP",dialogTitle]
                          delegate: self
                          cancelButtonTitle: NSLocalizedString(@"设置",nil)
                          otherButtonTitles: NSLocalizedString(@"进入",nil), nil];
    [alert show];
    [alert release];

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {
        case 0: 
        {       
            [self openSettingDialog];
        }
            break;
            
        case 1: 
        {
            // 確定
            [self jumpToUserMainView];
        }
            break;
    }
}
- (void) jumpToUserMainView
{
     [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.infoView = nil;
    self.activityView = nil;
   
    
    clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
    // MainUserUIViewController *vc = [[MainUserUIViewController alloc] init];
    
    MainViewController *vc = [[MainViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    
     appDelegate.window.rootViewController = nav;
    
    [vc release];
    [nav release];

}
- (void) openSettingDialog
{
    settingdialogopend = YES;
    SettingViewController *vc = [[SettingViewController alloc] init];
    vc.controllerOpener = self;
    [self presentModalViewController:vc animated:NO];

}
-(void)settingCallback
{
    [self refreshBackGrounImage];
    
    [self dismissModalViewControllerAnimated:NO];
     self.gotoSettingBtn.hidden = NO;
    
    settingdialogopend = NO;
     [self latterStartSyncBackgrounThread];
    /*
     clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate startSyncBackgroundThread];
     */
    
}
-(IBAction) gotoSetting:(id)sender
{
    [self openSettingDialog];
}
@end
